package com.nommon.menu;

import com.nommon.R;
import com.nommon.tool.Button;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class GameView extends SurfaceView {

	private UpdateNDrawThread updateThread;
	private Joystick joystick;
	private Background background;
	private Airplane airplane;
	private Button button;
	
	
	public GameView(Context context) {
		super(context);
		updateThread = new UpdateNDrawThread(this);
		initUI();
		initObjects();
		getHolder().addCallback(new HolderCallBack());
	}

	private void initObjects() {
		background = new Background(BitmapFactory.decodeResource(getResources(), R.drawable.bg1));
		airplane = new Airplane(BitmapFactory.decodeResource(getResources(), R.drawable.f22));
		button = new Button(20, 20, 60, 60, "hallo");
	}

	private void initUI() {
		joystick = new Joystick(20, -20);
	}

	@Override
	protected void onDraw(Canvas canvas) {
		canvas.drawColor(Color.BLACK);
		background.draw(canvas);
		airplane.draw(canvas);
		joystick.draw(canvas);
		button.draw(canvas, 0, 0);
	}

	public void onUpdate(float deltaSec) {
		background.onUpdate(deltaSec);
		airplane.onUpdate(deltaSec, joystick.getJoystickState());
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
       return joystick.onTouchEvent(event)
    		   || super.onTouchEvent(event)
    		   || true;
	}
	
	
	
	// --------------------
	
	class HolderCallBack implements SurfaceHolder.Callback {
		public void surfaceDestroyed(SurfaceHolder holder) {
            boolean retry = true;
            updateThread.setRunning(false);
            while (retry) {
                   try {
                         updateThread.join();
                         retry = false;
                   } catch (InterruptedException e) {}
            }
     }


     @Override
     public void surfaceCreated(SurfaceHolder holder) {
            updateThread.setRunning(true);
            updateThread.start();
     }

		@Override
		public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
		}
	}

}
